<?php
// version 0.1 vom 18.7.11
// version 0.3 vom 25.11.11
// author: Burkhart Holznagel
// GNU GPL v2
// based on : http://www.ajaxlines.com/ajax/stuff/article/how_to_create_a_simple_webbased_chat_application.php
ini_set('session.use_trans_sid', 1);
session_start(); 
include ("post.php");

function loginForm(){
	echo '<div id="loginform">';
	alarmBlock();
	echo'<br><br><br>
	    <b> <font size="+2"> <center>Perchat your communication program</center></font></b>
	    <br>
	    <form name="myForm" action="index.php" method="post">
		<p>Please enter your chat-name (nick name) to continue:</p>
		<label for="name">Name:</label>
		<input type="text" name="name" id="name" title="enter your chat name" />
		<input type="submit" name="enter" id="enter" value="Enter" />
	    </form>
	    </div>
	    ';
}

function alarmBlock()	{
    echo "<div id=\"mailblocklogin\">";
    echo '<b> <center>Emergency aid</center></b><br>Mails(up to 4) To:<br>
	<table>
	<tr><th>';
    for ( $i=0; $i < $_SESSION['numMailAddresses']; $i++ )      {
    echo "<form name=\"mymail".$i."\"  id=\"mymail".$i."\"  action=\"index.php\" method=\"post\">";
    echo "<input type=\"hidden\" name=\"mymail\" value=\"$i\" >";
    echo "<input class=\"mymails\" name=\"myaddress\" id=\"myaddres".$i."\" type=\"text\"  title=\"enter a valid mail address and type newline to store\" size= \"28\" value=\"";echo $_SESSION['mailAddresses'][$i];echo "\">";
    echo "</form>"; }
    echo "</th>
	<th>
	<form action=\"index.php\" method=\"post\">
	<input class=\"myalarm\" name=\"alarmbutton\"  type=\"submit\" value=\"Alarm !!!\" title= \"click or touch here to send mails\" >
	</form>    </th>
	</tr>
	</table>";
    echo "<form action=\"index.php\" method=\"post\">";
    echo "<input class=\"mymailtext\" name=\"mymailtext\" id=\"mymailtext\" type=\"text\"  title=\"enter another mailtext here and type newline to store\"  size= \"44\" value=\"";echo $_SESSION['mailText'];
    echo "\"> Mail Text  </form>";
    echo "<form action=\"index.php\" method=\"post\">";
    echo "<input class=\"mailmails\" name=\"mailsender\" type=\"text\"  title=\"enter a valid send mail address (or try with empty address) and type newline to store \" size= \"28\" value=\"";echo $_SESSION['mailsender'];echo "\"> Mail from";
    echo "</form> </div>";
}
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<!--[if lt IE 9]>
<script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<title>My personal chat</title>
<link type="text/css" rel="stylesheet" href="style.css" />
<link rel="shortcut icon" type="image/x-icon" href="/perchat/myicon.jpg">
</head>
<body onLoad="pageScroll()">
<audio id="audio"  preload="auto" autobuffer >
 <source src="crossing.wav" type="audio/wav" />
 <source src="sound1a.mp3" type="audio/mpeg" />
     Your browser support not html5 audio tag
</audio> 
<!-- a hack for android audio -->
<video id="video"  preload="auto" width="0" autobuffer >
 <source src="sound1a.mp3" />
    Your browser support not html5 video tag
</video>

<script language="JavaScript">
phpVersion="<?php echo phpversion(); ?>";
if ( phpVersion.charAt(0) < 5)	{
    alert( "perchat needs php5 or higher!");
}
	
/*
 * MSIE 9.0
*/
document.write("Offizieller Name des Browsers: "+ navigator.appName + "<br>");
document.write("Spitzname des Browsers: " + navigator.appCodeName + "<br>");
document.write("Version: " + navigator.appVersion +"<br>");
document.write("HTTP-Identifikation des Browsers: " + navigator.userAgent +"<br>");
document.write("Plattform: " + navigator.platform +"<br>");
document.write("Eingestellte Sprache des Browsers: " + navigator.language +"<br>");

// -->
    var mobile = (/iphone|ipad|ipod|android|blackberry|mini|windows\sce|palm/i.test(navigator.userAgent.toLowerCase()));  
function pageScroll() {
    	window.scrollBy(0,150); // horizontal and vertical scroll increments
//    	scrolldelay = setTimeout('pageScroll()',100); // scrolls every 100 milliseconds
	if (mobile)
	    $("div#chatbox-smartphone").animate({ scrollTop: 1500 }, 'normal');
	else
	    $("div#chatbox").animate({ scrollTop: 1500 }, 'normal');
}
</script>

<?php
if(!isset($_SESSION['name'])){
    $_SESSION['textfile'] = "family.txt";
    $_SESSION['fileLines'] = 9;
    $_SESSION['sound']="0";
    $_SESSION['currentActualTextNumber']=0;
    $_SESSION['numLetters']=9;
    $_SESSION['numButtons']=3;
    $_SESSION['actualLetterNumber']=0;
    $_SESSION['charArray'][0]= array( "a","e","i","o","u","v","w","x","p");
    $_SESSION['charArray'][1]= array( "b","d","f","g","k","l","m","n","r");
    $_SESSION['charArray'][2]= array( "c","h","s","t","y","z","D","S","N");
    $_SESSION['letterMode']= "3letters";    
    $_SESSION['numMailAddresses']=4;
    $file = fopen('mailaddress.txt', "r") or exit("Unable to open file!".'mailaddress.txt');
    for ($i=0; $i < $_SESSION['numMailAddresses']; $i++)	$_SESSION['mailAddresses'][$i] = fgets($file,72);
    $file = fopen('mailtext.txt', "r") or exit("Unable to open file!".'mailtext.txt');
    $_SESSION['mailText'] = fgets($file,72);
    $file = fopen('mailsender.txt', "r") or exit("Unable to open file!".'mailsender.txt');
    $_SESSION['mailsender'] = fgets($file,72);

$empfaenger = "burkhart.holznagel@gmail.com";
$absendername = "Kontaktformular";
$absendermail = "burkhart.holznagel@ba-berlin.com";
$timestamp = time();
$datum = date("d.m.Y",$timestamp);
$uhrzeit = date("H:i",$timestamp);
$betreff = "ui3";
$text = "Hallo ".$datum." ".$uhrzeit;
mail($empfaenger, $betreff, $text, "From: $absendername <$absendermail>");

loginForm();        
    }
else	 {
    $file = fopen($_SESSION['textfile'], "r") or exit("Unable to open file!".$_SESSION['textfile']);
    for ($i=0; $i < $_SESSION['fileLines']; $i++)	$_SESSION['text'][$i] = fgets($file,72);
     $_SESSION['actualText']=$_SESSION['text'][0];
    fclose($file); 
?>
<div id="wrapper">
<!--<table  width="100%"><tr><th></th><th> -->
<div id="mailblock">
<form name="alarmbutton" action="index.php" method="post">
<center><b>Emergency aid<br></b></center>
<center><input class="myalarm" name="alarmbutton"  type="submit" value="Alarm !!!" title= "click or touch here to send mails"></center>
</form>
</div>

<!--</th><th></th></tr></table>-->
	<div id="menu">
		<p class="welcome">Welcome, <b><?php echo $_SESSION['name']; ?></b></p><br>
	<table  width="100%"> <tr>
	<th>
	<p class="clearchat"><a id="clear" href="#">Clear Chat</a></p>
	</th>
	
<script type="text/javascript">
	var sound = "<?php echo $_SESSION['sound']; ?>";
if (1) {
		if (sound == "0" )
		    document.write("<th><p class=\"sound\"><a id=\"sound\" href=\"#\">Sound If Chat Message</a></p></th>");
		else	
		    document.write("<th><p class=\"sound\"><a id=\"sound\" href=\"#\">No Sound If Chat Message</a></p></th>");
	}
	</script>
	<th>
		<p class="logout"><a id="exit" href="#">Exit Chat</a></p>
	</th>
	</tr></table>
		<div style="clear:both"></div>
	</div>	
    <script type="text/javascript">  

//    mobile = 1;
    if (mobile) {  document.write("<div id=\"chatbox-smartphone\">");
		}  
    else	{
		    document.write("<div id=\"chatbox\">");
		}
</script>

<?php
	if(file_exists("log.html") && filesize("log.html") > 0){
		$handle = fopen("log.html", "r");
		$contents = fread($handle, filesize("log.html"));
		fclose($handle);
		echo $contents;
	}
?>
</div>
<form name="message" id="message">
<input name="usermsg" title="insert a chat message here" type="text" id="usermsg" size="63" value="" onclick="clicksubmit()" />
</form>

<?php 
echo "<div name \"letters\" id=\"letters\" style=\"text-align:center;\">";	echo "</div>";
echo "<div  name=\"refresh\"  id=\"refresh\" style=\"text-align:center;\">";	echo "</div>";
echo "<div name=\"textmodule\" id=\"textmodule\" >";				echo "</div>";
echo "<spam></spam>";
?>

<script type="text/javascript" src="jquery.min.js"></script>

<!--<script type="text/javascript" src="/usr/share/javascript/jquery/jquery.min.js"></script>-->
<!--<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.min.js"></script>-->
<!--<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>-->

<script src="http://cdn.jquerytools.org/1.2.6/tiny/jquery.tools.min.js"></script>

<script type="text/javascript">
/*	
	
		$("#message :usermsg").tooltip({

	// place tooltip on the right edge
	position: "center right",

	// a little tweaking of the position
	offset: [-2, 10],

	// use the built-in fadeIn/fadeOut effect
	effect: "fade",

	// custom opacity setting
	opacity: 0.7

});

*/

// jQuery Document
$(document).ready(function(){
	      var before;
    //If user submits the form
	$("form#message").submit(function(){	
		textInChat($("input#usermsg").val());
		$("input#usermsg").attr("value", "");
		return false;
	});

	//Load the file containing the chat log
	function loadLog(){

	      if (mobile) { 
		    
		var oldscrollHeight = 1000 - 20;//$("#chatbox-smartphone").attr("scrollHeight") - 20;
		$.ajax({
			url: "log.html",
			cache: false,
			success: function(html){
				$("div#chatbox-smartphone").html(html); //Insert chat log into the #chatbox div				
				//var newscrollHeight = $("#chatbox-smartphone").attr("scrollHeight") - 20;
			//	if(newscrollHeight > oldscrollHeight){
					$("div#chatbox-smartphone").animate({ scrollTop: 1000+20 }, 'normal'); //Autoscroll to bottom of div
			//	}
		  	},
		});
			}  
		else	{
		    
		var oldscrollHeight = $("div#chatbox").attr("scrollHeight") - 20;
		$.ajax({
			url: "log.html",
			cache: false,
			success: function(html){
				$("div#chatbox").html(html); //Insert chat log into the #chatbox div				
				var newscrollHeight = $("div#chatbox").attr("scrollHeight") - 20;
				if(newscrollHeight > oldscrollHeight){
					$("div#chatbox").animate({ scrollTop: newscrollHeight }, 'normal'); //Autoscroll to bottom of div
				}
		  	},
		});
    }
    
var after = $("div").length;
if (typeof before == "undefined") {
before= after;  
}
if (before < after)	{
      var thissound=document.getElementById('audio');
      var thisvideo=document.getElementById('video');
var soundOut = <?php echo $_SESSION['sound']; ?>;
if (soundOut)	{
if (mobile) { thisvideo.play();}	// it works for android!
else
    thissound.play();
	    }

//	<?php echo "$(\"spam\").text(before + \"  \" + after);"; ?>   
}
before=after;
	}

	setInterval (loadLog, 2500);	//Reload file every 2.5 seconds
	
	$("div#letters").load("letters.php");
	setInterval(function() {
          $("div#letters").load('letters.php');
		}, 3000); 
       
	$("div#refresh").load("refresh.php");
	setInterval(function() {
          $("div#refresh").load('refresh.php');
		}, 4000);

        $("div#textmodule").load("textmodules.php");      

	//If user wants to end session
	$("a#exit").click(function(){
		var exit = confirm("Are you sure you want to end the session?");1
		if(exit==true){window.location = 'index.php?logout=true';}		
	});
	$("a#clear").click(function(){
		var clear = confirm("Are you sure you want to clear the chat?");1
		if(clear==true){window.location = 'index.php?clearchat=true';}		
	});
	$("a#sound").click(function(){
	    window.location = 'index.php?sound=1';
	});	
});

    
function touchsubmit()	{
    		var clientmsg = $("input#selText").val();
		if (clientmsg.length > 36)	{
		    clientmsg=clientmsg.substring(0,36) + clientmsg.substring(37,clientmsg.length);   
		    }
		textInChat(clientmsg);
}
 
       
function clicksubmit()	{
    		var clientmsg = $("input#usermsg").val();
		    textInChat(clientmsg);
		    $("input#usermsg").attr("value", "");
}

function mysubmit(nr)	{ 
    textInChat( $("input#mytext"+nr).val());	
//	document.message.usermsg.focus();
//	document.message.usermsg.select();
//	CopiedTxt = document.selection.createRange();
//	CopiedTxt.execCommand("Copy"); // doesnt work with firefox
    return true;
}

function mylettersubmit(nr)	{
    if (  $("input#myletterchar"+nr).val() == "N")	{		// new line
	$.post("post.php", {mode: "3letters"});
	if ($("input#usermsg").val() != "")	{
	    $.post("post.php", {chattext: "true", text: $("input#usermsg").val() });
	    $("input#usermsg").attr("value","");
	    $("div#textmodule").load("textmodules.php");
		}
	return;
    }
    if (  $("input#myletterchar"+nr).val() == "S")	{	// space
	     $("input#usermsg").attr("value",$("input#usermsg").val() + " ");
	     return;
    }
    if (  $("input#myletterchar"+nr).val() == "D")	{	// back space
	if ($("input#usermsg").val() != "")	{
	    $("input#usermsg").attr("value",$("input#usermsg").val().substring(0,$("input#usermsg").val().length-1));
		}
    return;
    }
   $.post("post.php", {mode: "6letters"});
   $("input#usermsg").attr("value",$("input#usermsg").val() + $("input#myletterchar"+nr).val());
   $("div#textmodule").load("textmodules.php");
}

function textInChat(myText)	{
     if ( myText != "")	{
    	$.post("post.php", {chattext: "true", text: myText});
     }
}

</script>

<?php
}
?>

</body>
</html>
